package com.backend.controller;

import com.backend.entity.User;
import com.backend.repository.UserRepository;
import com.backend.tool.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class Login {
    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    Result login(@RequestBody User user) {
        String email = user.getEmail();
        String password = user.getPassword();

        User u = userRepository.findUserByEmail(email);
        System.out.println("login:" + email + " " + password);
        if (u == null) return Result.error(201, "用户不存在");
        if (u.getPassword().equals(password)) {
            Map map = new HashMap();
            map.put("id",u.getId());
            map.put("name",u.getName());
            map.put("password",u.getPassword());
            String token = JwtUtils.createToken(map);

            Map frontMap = new HashMap();
            frontMap.put("id",u.getId());
            frontMap.put("name",u.getName());
            frontMap.put("email",u.getEmail());
            frontMap.put("token",token);
            return Result.success(frontMap);
        }
        return Result.error(201, "邮箱或密码错误");
    }

    @PostMapping("/regist")
    Result regist(@RequestBody User user) {
        String username = user.getName();
        String email = user.getEmail();
        if(email.equals("")){
            return Result.error(202, "邮箱不合法");
        }
        String password = user.getPassword();
        System.out.println("regist:" + username + " "+email+" " + password);

        User u = userRepository.findUserByEmail(email);
        if (u != null) {
            return Result.error(202, "邮箱已被使用");
        }
        user.setId(userRepository.getMaxId() + 1);
        userRepository.save(user);
        return Result.success(user.toFront());
    }
}
